from django.db.models import Q
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from user.models import UserModel
from utils.jwttool import tooljwt


# Create your views here.

class LoginView(APIView):
    def post(self, request):
        account = request.data.get('account')
        password = request.data.get('password')
        user = UserModel.objects.filter(Q(username=account) | Q(phone=account)).first()
        if user is None:
            return Response({'code': 400, 'message': '用户不存在'})
        if user.password == password:
            data = {
                'id': user.id,
                'role': user.role.id,
                'token': tooljwt.getToken(user.id, account)
            }
            return Response({'code': 200, 'message': '登录成功', 'data': data})
        else:
            return Response({'code': 400, 'message': '密码错误'})
